package com.xatalk.assistant;

import android.accessibilityservice.AccessibilityService;
import android.annotation.SuppressLint;
import android.app.Notification;
import android.app.PendingIntent;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.KeyEvent;
import android.view.accessibility.AccessibilityEvent;
import android.view.accessibility.AccessibilityNodeInfo;
import android.widget.Toast;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.List;

/**
 * Created by Administrator on 2018/3/16 0016.
 */

public class AutoRepyUtils {
    private Context context;
    private AccessibilityEvent event;
    private AccessibilityService accessibilityService;
    public AutoRepyUtils(Context context,AccessibilityEvent event,AccessibilityService accessibilityService){
        this.context=context;
        this.accessibilityService=accessibilityService;
        this.event=event;
        onCreate();
    }
    private void onCreate(){
        int eventType = event.getEventType();
        switch (eventType) {
            case AccessibilityEvent.TYPE_NOTIFICATION_STATE_CHANGED:
                if (SharedPreferHelper.getBoolean(context, "setting", "statue")) {
                    onNotificationChange(event);
                }

                break;
            case AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED:

                break;
        }
    }
    private void onNotificationChange(AccessibilityEvent event) {
        List<CharSequence> textList = event.getText();
        if (!textList.isEmpty()) {
            for (CharSequence text : textList) {
                Log.d("text", text.toString());
                if (text.toString().length() > 0) {

                    openSendUI(event, text.toString());
                }
            }
        }
    }
    /**
     * @param event
     */
    private void openSendUI(AccessibilityEvent event, String text) {
        if (event.getParcelableData() != null
                && event.getParcelableData() instanceof Notification) {
            Notification notification = (Notification) event
                    .getParcelableData();
            PendingIntent pendingIntent = notification.contentIntent;
            try {
                pendingIntent.send();
            } catch (PendingIntent.CanceledException e) {
                e.printStackTrace();
            }
        }
        Toast.makeText(context, text, Toast.LENGTH_LONG).show();
        String[] cc = text.split(":");
        if (!queryLocalData(cc[1].trim())) {
            queryChatData(cc[1].trim(), cc[0].trim());
        }

    }
    private boolean queryLocalData(String textInfo) {
        ReplyKeyDataUtils replyKeyDataUtils = new ReplyKeyDataUtils(context);
        List<ReplyKeyBean> list = replyKeyDataUtils.getReplyData(textInfo);
        Log.d("key", list.size() + "");
        if (list.size() > 0) {
            final String msg = list.get(0).getMsg();
            Log.d("key", msg);
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    if (fill(msg)) {
                        send();
                    }
                }
            }, 1000);

            return true;
        }
        return false;
    }

    private void queryChatData(String textInfo, String userId) {

        String url = "http://www.tuling123.com/openapi/api?key=c3b50aa0e04c4069bc3bfe6ec5eb9e66&info=" +
                textInfo +
                "&userid=" + userId;

        OkHttpManager.getAsyn(url, new OkHttpManager.ResultCallback() {
            @Override
            public void onError(Exception e) {
                Toast.makeText(context, "请求失败", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onResponse(String string) {
                Log.d("1", string);
                try {
                    JSONObject jsonObject = new JSONObject(string);
                    if (jsonObject.getInt("code") == 100000) {
                        final String resText = jsonObject.getString("text");
                        new Handler().postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                if (fill(resText)) {
                                    send();
                                }
                            }
                        }, 1000);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }
    private boolean fill(String msg) {
        AccessibilityNodeInfo rootNode = accessibilityService.getRootInActiveWindow();
        if (rootNode != null) {
            return findEditText(rootNode, msg);
        }
        return false;
    }
    private boolean findEditText(AccessibilityNodeInfo rootNode, String content) {
        int count = rootNode.getChildCount();
        for (int i = 0; i < count; i++) {
            AccessibilityNodeInfo nodeInfo = rootNode.getChild(i);
            if (nodeInfo == null) {
                continue;
            }
            if ("android.widget.EditText".equals(nodeInfo.getClassName())) {
                Bundle arguments = new Bundle();
                arguments.putInt(AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT,
                        AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD);
                arguments.putBoolean(AccessibilityNodeInfo.ACTION_ARGUMENT_EXTEND_SELECTION_BOOLEAN,
                        true);
                nodeInfo.performAction(AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY,
                        arguments);
                nodeInfo.performAction(AccessibilityNodeInfo.ACTION_FOCUS);
                ClipData clip = ClipData.newPlainText("label", content);
                ClipboardManager clipboardManager = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
                clipboardManager.setPrimaryClip(clip);
                nodeInfo.performAction(AccessibilityNodeInfo.ACTION_PASTE);
                return true;
            }

            if (findEditText(nodeInfo, content)) {
                return true;
            }
        }

        return false;
    }
    /**
     * 寻找窗体中的“发送”按钮，并且点击。
     */
    @SuppressLint("NewApi")
    private void send() {
        AccessibilityNodeInfo nodeInfo = accessibilityService.getRootInActiveWindow();
        if (nodeInfo != null) {
            List<AccessibilityNodeInfo> list = nodeInfo
                    .findAccessibilityNodeInfosByText("发送");
            if (list != null && list.size() > 0) {
                for (AccessibilityNodeInfo n : list) {
                    if (n.getClassName().equals("android.widget.Button") && n.isEnabled()) {
                        n.performAction(AccessibilityNodeInfo.ACTION_CLICK);
                    }
                }

            } else {
                List<AccessibilityNodeInfo> liste = nodeInfo
                        .findAccessibilityNodeInfosByText("Send");
                if (liste != null && liste.size() > 0) {
                    for (AccessibilityNodeInfo n : liste) {
                        if (n.getClassName().equals("android.widget.Button") && n.isEnabled()) {
                            n.performAction(AccessibilityNodeInfo.ACTION_CLICK);
                        }
                    }
                }
            }
        }
        pressBackButton();
        back2Home();
    }
    /**
     * 模拟back按键
     */
    private void pressBackButton() {
        Runtime runtime = Runtime.getRuntime();
        try {
            runtime.exec("input keyevent " + KeyEvent.KEYCODE_BACK);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 回到系统桌面
     */
    private void back2Home() {
        Intent home = new Intent(Intent.ACTION_MAIN);

        home.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        home.addCategory(Intent.CATEGORY_HOME);
        context.startActivity(home);
      /*  Intent it = new Intent("com.xatalk.intent.main");
        it.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(it);*/
    }
}
